﻿package modular {
	import modular.module.Module;				

	/**
	 * @author Administrator
	 */
	public class ModuleSetItem {
		
		protected var _info:ModuleInfo;
		protected var instance:Module;
		protected var transfered:Boolean;

		public function ModuleSetItem( xml:XML ) {
			this._info = new ModuleInfo( xml );
			transfered = false;
		}
		
		public function createInstanceOn( msl:ModuleSetLoader ):void {
			_info.parentLoader = msl;
			if( instance == null ) {
				var _class:Class = Library.getClassOf( _info.className, _info.libraryPath );
				instance = new _class();
				if( !isNaN( _info.position.x ) ) instance.x = _info.position.x;
				if( !isNaN( _info.position.y ) ) instance.y = _info.position.y;
				if( !isNaN( _info.width ) ) instance.width = _info.width;
				if( !isNaN( _info.height ) ) instance.height = _info.height;
				instance.info = _info;
			}
		}
		
		public function hasInstance():Boolean {
			return instance != null;
		}
		
		public function equals( foreign:ModuleSetItem ):Boolean {
			return _info.equals( foreign.info);
		}

		public function show():void {
			if( instance != null && !transfered ) instance.show();
		}
		
		public function hide():void {
			if( instance != null ) instance.hide();
		}
		
		public function get info():ModuleInfo {
			return _info;
		}
		
		public function get module():Module {
			return instance;
		}
		
		public function transfer( old:ModuleSetItem ):void {
			instance = old.module;
			_info.parentLoader = old.info.parentLoader;
			instance.info = _info;
			transfered = true;
		}
		
		public function getLibrary():String {
			return _info.libraryPath;
		}
		
		public function getModuleByID( id:String ):Module {
			if( module is ModuleSetLoader ) {
				return ModuleSetLoader( module ).getModuleByID( id );
			} else {
				return ( info.id == id ) ? module : null;
			}
		}
		
		public function getModuleByClass( className:String ):Module {
			if( module is ModuleSetLoader ) {
				return ModuleSetLoader( module ).getModuleByClass( className );
			} else {
				return ( info.className == className ) ? module : null;
			}
		}
		
		public function destroy():void {
			instance.destroy();
			instance = null;
			_info = null;
		}
		
	}
}
